﻿using System;
using System.IO;
using Microsoft.Live;

namespace Store.WP7.Framework
{
    public class SkydriveService
    {
        public const string RequiredScopes = "wl.signin wl.basic wl.skydrive wl.skydrive_update";
        public const string ClientId = "000000004C07A518";

        private LiveConnectSession _session;
        private LiveConnectClient _liveConnectClient;

        public SkydriveService(LiveConnectSession session)
        {
            if (session == null)
                throw new ArgumentNullException("session");

            _session = session;
            _liveConnectClient = new LiveConnectClient(_session);
            _liveConnectClient.UploadCompleted += OnUploadCompleted;
        }

        public void Logout()
        {
            _session = null;
            _liveConnectClient = null;
        }

        private Action _uploadCallback;
        private bool _uploadInProgress = false;

        public void UploadFile(byte[] buffer, string fileName, Action callback)
        {
            if (!_uploadInProgress)
            {
                _uploadInProgress = true;
                _uploadCallback = callback;
                _liveConnectClient.UploadAsync("/me/skydrive", fileName, new MemoryStream(buffer));
            }
        }

        private void OnUploadCompleted(object sender, LiveOperationCompletedEventArgs e)
        {
            if (_uploadInProgress && _uploadCallback != null)
            {
                _uploadCallback();
                _uploadCallback = null;
                _uploadInProgress = false;
            }
        }
    }
}
